package com.outdoor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.outdoor.exception.BusinessException;
import com.outdoor.model.entity.Team;
import com.outdoor.model.entity.Trip;
import com.outdoor.model.entity.User;
import com.outdoor.model.enums.ActivityType;
import com.outdoor.model.enums.TripStatus;
import com.outdoor.mapper.TripMapper;
import com.outdoor.service.TeamService;
import com.outdoor.service.TripService;
import com.outdoor.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 行程服务实现
 * 
 * @author OutdoorTeam
 * @date 2025-05-18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TripServiceImpl implements TripService {

    private final TripMapper tripMapper;
    private final UserService userService;
    private final TeamService teamService;

    @Override
    public Trip createTrip(Trip tripRequest, Long organizerId) {
        User organizer = userService.getUserById(organizerId);
        Trip trip = Trip.builder()
                .name(tripRequest.getName())
                .activityType(tripRequest.getActivityType())
                .location(tripRequest.getLocation())
                .date(tripRequest.getDate())
                .description(tripRequest.getDescription())
                .status(tripRequest.getStatus() != null ? tripRequest.getStatus() : TripStatus.UPCOMING.name())
                .organizerId(organizerId)
                .photos("")
                .build();
        tripMapper.insert(trip);
        log.info("行程创建成功: {}, 组织者: {}", trip.getName(), organizer.getUsername());
        userService.incrementTripsCount(organizerId);
        return trip;
    }

    @Override
    public Trip createTripFromTeam(Long teamId, Long organizerId) {
        Team team = teamService.getTeamById(teamId);
        User organizer = userService.getUserById(organizerId);
        if (!team.getLeaderId().equals(organizerId)) {
            throw new BusinessException("UNAUTHORIZED", "只有团队领队可以创建行程");
        }
        if (team.getTripId() != null) {
            throw new BusinessException("TRIP_EXISTS", "团队已有关联行程");
        }
        Trip trip = Trip.builder()
                .name(team.getName())
                .activityType(team.getActivityType())
                .location(team.getLocation())
                .date(team.getDate())
                .description(team.getDescription())
                .status(TripStatus.APPLYING.name())
                .organizerId(organizerId)
                .teamId(teamId)
                .photos("")
                .build();
        tripMapper.insert(trip);
        
        // 更新团队关联行程
        team.setTripId(trip.getId());
        teamService.updateTeamTrip(team);
        
        log.info("从团队 {}, 创建行程成功: {}", team.getName(), trip.getName());
        return trip;
    }

    @Override
    public Trip getTripById(Long id) {
        Trip trip = tripMapper.selectById(id);
        if (trip == null) {
            throw new BusinessException("TRIP_NOT_FOUND", "行程不存在");
        }
        return trip;
    }

    @Override
    public List<Trip> getTripsByTeamId(Long teamId) {
        QueryWrapper<Trip> query = new QueryWrapper<>();
        query.eq("team_id", teamId);
        return tripMapper.selectList(query);
    }

    @Override
    public Trip updateTripStatus(Long id, TripStatus status, Long currentUserId) {
        Trip trip = getTripById(id);
        if (!trip.getOrganizerId().equals(currentUserId)) {
            throw new BusinessException("UNAUTHORIZED", "只有行程组织者可以更新行程状态");
        }
        trip.setStatus(status.name());
        tripMapper.updateById(trip);
        log.info("行程状态更新成功: {}, 新状态: {}", trip.getName(), status);
        return trip;
    }

    @Override
    public Trip addTripPhoto(Long id, String photoUrl, Long currentUserId) {
        Trip trip = getTripById(id);
        if (!trip.getOrganizerId().equals(currentUserId)) {
            throw new BusinessException("UNAUTHORIZED", "只有行程组织者可以添加照片");
        }
        
        // 处理照片字符串
        String currentPhotos = trip.getPhotos();
        List<String> photoList = stringToList(currentPhotos);
        photoList.add(photoUrl);
        trip.setPhotos(listToString(photoList));
        
        tripMapper.updateById(trip);
        log.info("行程照片添加成功: {}", trip.getName());
        return trip;
    }
    
    @Override
    public IPage<Trip> getTripsByOrganizer(Long userId, Page<Trip> page) {
        QueryWrapper<Trip> query = new QueryWrapper<>();
        query.eq("organizer_id", userId);
        return tripMapper.selectPage(page, query);
    }
    
    @Override
    public IPage<Trip> getTripsByStatus(TripStatus status, Page<Trip> page) {
        QueryWrapper<Trip> query = new QueryWrapper<>();
        query.eq("status", status.name());
        return tripMapper.selectPage(page, query);
    }
    
    @Override
    public IPage<Trip> getTripsByActivityTypeAndStatus(ActivityType activityType, TripStatus status, Page<Trip> page) {
        QueryWrapper<Trip> query = new QueryWrapper<>();
        query.eq("activity_type", activityType);
        query.eq("status", status.name());
        return tripMapper.selectPage(page, query);
    }
    
    @Override
    public List<String> getTripPhotos(Trip trip) {
        return stringToList(trip.getPhotos());
    }
    
    /**
     * 将逗号分隔的字符串转为List
     */
    private List<String> stringToList(String str) {
        if (str == null || str.isEmpty()) {
            return new ArrayList<>();
        }
        return Arrays.stream(str.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
    }
    
    /**
     * 将List转为逗号分隔的字符串
     */
    private String listToString(List<String> list) {
        if (list == null || list.isEmpty()) {
            return "";
        }
        return String.join(",", list);
    }
} 